package server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * web应用类加载器
 * 
 * @author Lenovo
 *
 */
public class WebAppClassLoader extends ClassLoader {
	// 指定路径
	private String path;

	public WebAppClassLoader(String classPath) {
		this.path = classPath;
	}

	/**
	 * 重写findClass方法
	 * 
	 * @param className 是我们这个类的全路径
	 * @return
	 * @throws ClassNotFoundException
	 */
	@Override
	protected Class<?> findClass(String className) throws ClassNotFoundException {
		Class log = null;
		// 获取该class文件字节码数组
		byte[] classData = getData(className);

		if (classData != null) {
			// 将class的字节码数组转换成Class类的实例
			log = defineClass(className, classData, 0, classData.length);
		}
		return log;
	}

	/**
	 * 将class文件转化为字节码数组
	 * 
	 * @return
	 */
	private byte[] getData(String className) {
		String classFilePath = this.path + "\\" + className.replace(".", "\\") + ".class";
		File file = new File(classFilePath);
		if (file.exists()) {
			FileInputStream in = null;
			ByteArrayOutputStream out = null;
			try {
				in = new FileInputStream(file);
				out = new ByteArrayOutputStream();

				byte[] buffer = new byte[1024];
				int size = 0;
				while ((size = in.read(buffer)) != -1) {
					out.write(buffer, 0, size);
				}

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					in.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
			return out.toByteArray();
		} else {
			return null;
		}
	}

	@Override
	public InputStream getResourceAsStream(String name) {
		try {
			return new FileInputStream(new File(this.path + "\\" + name));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String toString() {
		return "WebAppClassLoader [path=" + path + "]";
	}

}
